/*
 * Created by weibo on 2020/3/17.
 */
import Vue from 'vue'
import Storage from '@/assets/js/storage.js'
import CryptoJS from 'crypto-js/crypto-js'

var child_process = require('child_process')
const { execCmd } = require('child_process')
const KEY = CryptoJS.enc.Utf8.parse('aad105faac054f05')
const IV = CryptoJS.enc.Utf8.parse('efde119241dc47dc')

//生产环境灰度账号
const gray = []

function isEmpty(val) {
  if (val === null || val === undefined || val === '') {
    return true
  }
  return false
}

function downFile(url) {
  let a = document.createElement('a')
  a.href = url
  a.click()
}

function timeFormat(val) {
  var hour = val.getHours() //得到小时
  var minu = val.getMinutes() //得到分钟
  var sec = val.getSeconds() //得到秒
  if (hour < 10) hour = '0' + hour
  if (minu < 10) minu = '0' + minu
  if (sec < 10) sec = '0' + sec
  return hour + ':' + minu + ':' + sec
}

function jsonToString(data) {
  let str = []
  for (let p in data) {
    if (Object.prototype.hasOwnProperty.call(data, p)) {
      str.push(encodeURIComponent(p) + '=' + encodeURIComponent(data[p]))
    }
  }
  return str.join('&')
}

//加密
function Encrypt(word, keyStr, ivStr) {
  let key = KEY
  let iv = IV

  if (keyStr) {
    key = CryptoJS.enc.Utf8.parse(keyStr)
    iv = CryptoJS.enc.Utf8.parse(ivStr)
  }

  let srcs = CryptoJS.enc.Utf8.parse(word)
  var encrypted = CryptoJS.AES.encrypt(srcs, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.ZeroPadding
  })
  // console.log("-=-=-=-", encrypted.ciphertext)
  return CryptoJS.enc.Base64.stringify(encrypted.ciphertext)
}

function assignTokenJson(url) {
  return ''
}
//按资源池更改api_path
const API_PATH = process.env.VUE_APP_API_PATH + '/'

export default {
  isEmpty,
  Encrypt,
  downFile,
  timeFormat,
  jsonToString,
  API_PATH,
  /*
   *
   *
   * 以下为封装的axios方法
   */
  axiosGet(url, params = {}) {
    url = API_PATH + url + assignTokenJson(url)
    return new Promise((resolve, reject) => {
      Vue.axios
        .get(url, {
          params: params
        })
        .then(response => {
          resolve(response.data)
        })
        .catch(err => {
          reject(err)
        })
    })
  },
  //post
  axiosPost(url, data = {}) {
    url = API_PATH + url + assignTokenJson(url)
    return new Promise((resolve, reject) => {
      Vue.axios.post(url, data).then(
        response => {
          resolve(response.data)
        },
        err => {
          reject(err)
        }
      )
    })
  },
  axiosPostJson(url, data = {}) {
    url = API_PATH + url + assignTokenJson(url)
    return new Promise((resolve, reject) => {
      Vue.axios
        .post(url, data, {
          headers: {
            'Content-Type': 'application/json'
          }
        })
        .then(
          response => {
            resolve(response.data)
          },
          err => {
            reject(err)
          }
        )
    })
  },
  //PUT
  axiosPut(url, data = {}) {
    url = API_PATH + url + assignTokenJson(url)
    return new Promise((resolve, reject) => {
      Vue.axios.put(url, data).then(
        response => {
          resolve(response.data)
        },
        err => {
          reject(err)
        }
      )
    })
  },
  //DELETE
  axiosDelete(url, data = {}) {
    url = API_PATH + url + assignTokenJson(url)
    return new Promise((resolve, reject) => {
      Vue.axios.delete(url, data).then(
        response => {
          resolve(response.data)
        },
        err => {
          reject(err)
        }
      )
    })
  },
  //与VUEX相结合的方法
  postAction(url, params, commit, clearMutation, requestMutation) {
    url = API_PATH + url + assignTokenJson(url)
    return Vue.axios
      .post(url, params)
      .then(response => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        if (response.success) {
          if (requestMutation !== '') {
            commit(requestMutation, response.data)
          }
          return Promise.resolve(response.data)
        } else {
          return Promise.reject(
            isEmpty(response.data) || isEmpty(response.data.errorMessage)
              ? {
                  errorMessage: '操作失败！'
                }
              : response.data
          )
        }
      })
      .catch(error => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        return Promise.reject(error)
      })
  },
  postJSONAction(url, params, commit, clearMutation, requestMutation) {
    url = API_PATH + url + assignTokenJson(url)
    return Vue.axios
      .post(url, params, {
        headers: {
          'Content-Type': 'application/json'
        }
      })
      .then(response => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        if (response.success) {
          if (requestMutation !== '') {
            commit(requestMutation, response.data)
          }
          return Promise.resolve(response.data)
        } else {
          return Promise.reject(
            isEmpty(response.data)
              ? {
                  errorMessage: '操作失败！'
                }
              : response.data
          )
        }
      })
      .catch(error => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        return Promise.reject(error)
      })
  },
  postDWLDAction(url, params, commit, clearMutation, requestMutation) {
    url = API_PATH + url + assignTokenJson(url)
    return Vue.axios
      .post(url, params, {
        headers: {
          'Content-Type': 'application/json'
        },
        responseType: 'blob'
      })
      .then(response => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        if (requestMutation !== '') {
          commit(requestMutation, response.data)
        }
        return Promise.resolve(response.data)
      })
      .catch(error => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        return Promise.reject(error)
      })
  },
  getAction(url, commit, clearMutation, requestMutation) {
    url = API_PATH + url + assignTokenJson(url)
    return Vue.axios
      .get(url)
      .then(response => {
        if (clearMutation && clearMutation !== '') {
          commit(clearMutation)
        }
        if (response.success) {
          if (requestMutation !== '') {
            commit(requestMutation, response.data)
          }
          return Promise.resolve(response.data)
        } else {
          return Promise.reject(
            isEmpty(response.data)
              ? {
                  errorMessage: '操作失败！'
                }
              : response.data
          )
        }
      })
      .catch(error => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        return Promise.reject(error)
      })
  },
  getDWLDAction(url, commit, clearMutation, requestMutation) {
    url = API_PATH + url + assignTokenJson(url)
    return Vue.axios
      .get(url, {
        headers: {
          'Content-Type': 'application/json'
        },
        responseType: 'blob'
      })
      .then(response => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        if (requestMutation !== '') {
          commit(requestMutation, response.data)
        }
        return Promise.resolve(response.data)
      })
      .catch(error => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        return Promise.reject(error)
      })
  },
  putAction(url, params, commit, clearMutation, requestMutation) {
    url = API_PATH + url + assignTokenJson(url)
    return Vue.axios
      .put(url, params)
      .then(response => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        if (response.success) {
          if (requestMutation !== '') {
            commit(requestMutation, response.data)
          }
          return Promise.resolve(response.data)
        } else {
          return Promise.reject(
            isEmpty(response.data) || isEmpty(response.data.errorMessage)
              ? {
                  errorMessage: '操作失败！'
                }
              : response.data
          )
        }
      })
      .catch(error => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        return Promise.reject(error)
      })
  },
  putJSONAction(url, params, commit, clearMutation, requestMutation) {
    url = API_PATH + url + assignTokenJson(url)
    return Vue.axios
      .put(url, params, {
        headers: {
          'Content-Type': 'application/json'
        }
      })
      .then(response => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        if (response.success) {
          if (requestMutation !== '') {
            commit(requestMutation, response.data)
          }
          return Promise.resolve(response.data)
        } else {
          return Promise.reject(
            isEmpty(response.data) || isEmpty(response.data.errorMessage)
              ? {
                  errorMessage: '操作失败！'
                }
              : response.data
          )
        }
      })
      .catch(error => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        return Promise.reject(error)
      })
  },
  deleteAction(url, commit, clearMutation, requestMutation) {
    url = API_PATH + url + assignTokenJson(url)
    return Vue.axios
      .delete(url)
      .then(response => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        if (response.success) {
          if (requestMutation !== '') {
            commit(requestMutation, response.data)
          }
          return Promise.resolve(response.data)
        } else {
          return Promise.reject(
            isEmpty(response.data)
              ? {
                  errorMessage: '操作失败！'
                }
              : response.data
          )
        }
      })
      .catch(error => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        return Promise.reject(error)
      })
  },
  deleteJSONAction(url, params, commit, clearMutation, requestMutation) {
    url = API_PATH + url + assignTokenJson(url)
    return Vue.axios
      .delete(url, {
        data: params,
        headers: {
          'Content-Type': 'application/json'
        }
      })
      .then(response => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        if (response.success) {
          if (requestMutation !== '') {
            commit(requestMutation, response.data)
          }
          return Promise.resolve(response.data)
        } else {
          return Promise.reject(
            isEmpty(response.data)
              ? {
                  errorMessage: '操作失败！'
                }
              : response.data
          )
        }
      })
      .catch(error => {
        if (clearMutation !== '') {
          commit(clearMutation)
        }
        return Promise.reject(error)
      })
  },
  //复制功能
  copy(msg) {
    let input = document.createElement('input')
    input.value = msg
    document.body.appendChild(input)
    input.select()
    document.execCommand('copy')
    document.body.removeChild(input)
    Vue.prototype.$message.success('复制成功!')
  },
  generateUUID() {
    let d = new Date().getTime()
    if (window.performance && typeof window.performance.now === 'function') {
      d += performance.now()
    }
    let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      let r = (d + Math.random() * 16) % 16 | 0
      d = Math.floor(d / 16)
      return (c == 'x' ? r : (r & 0x3) | 0x8).toString(16)
    })
    return uuid.substr(-4)
  },
  goToUrl(url, isNew = true) {
    if (!isNew) {
      top.location = url
    } else {
      window.open(url)
    }
  },
  dataToFile(dataurl) {
    var bstr = atob(dataurl)
    var n = bstr.length
    var u8arr = new Uint8Array(n)
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    return new Blob([u8arr], { type: 'doc' })
  }
}
